<template>
  <div class="dashboard-container">
    <div class="dashboard-title">
      <div>组织架构</div>
      <div class="rtList">
        <div class="search"><Input v-model="keyword" type="text" size="mini" placeholder="请输入姓名、工号、手机号" @input="setKeyword" /> <span class="icon" @click="init()">&#xe621;</span></div>
        <div class="aLink" @click="()=> importMember = true"> 导入成员</div>
        <div v-show="dapartmentInfo" class="aLink" @click="dialogVisibleHandle('编辑部门')">编辑部门</div>
        <div v-show="!dapartmentInfo" class="aLink" style="color: #ccc">编辑部门</div>
      </div>
    </div>
    <div class="dashboard-content">
      <div class="sidebarBox">
        <div class="addDepartment" @click="dialogVisibleHandle('添加部门')">添加部门</div>
        <div class="staffTree">
          <el-tree
            :data="orgList"
            node-key="label"
            :props="defaultProps"
            :highlight-current="true"
            :expand-on-click-node="false"
            :default-expanded-keys="[`${companyName}`]"
            accordion
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="minCont">
        <div class="contTitle">
          <span @click="dialogVisibleHandle('添加成员')">添加成员</span> <span @click="dialogVisibleHandle('删除确认')">批量删除</span><span @click="dialogVisibleHandle('调整部门')">调整部门</span></div>
        <div class="tableItem">
          <el-table ref="multipleTable" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="43" />
            <el-table-column prop="userName" label="姓名" width="120" />
            <el-table-column prop="post" label="职位" />
            <el-table-column prop="workNumber" label="工号" />
            <el-table-column prop="mobile" label="手机号" />
            <el-table-column label="邮箱" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.email }}</template>
            </el-table-column>
            <el-table-column label="操作" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <span class="action" @click="dialogVisibleHandle('调整部门', scope.row.id)">调整部门</span>
                <span class="action" @click="dialogVisibleHandle('删除确认', scope.row.id)">删除</span>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="total >= 10" class="pageList">
            <el-pagination
              layout="prev, pager, next"
              :total="total"
              @current-change="handlePageChange"
            />
          </div>
          <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <div v-show="title == '添加成员'" class="itemBox">
              <div class="item"><span class="tit">姓名：</span><input v-model="addMember.userName" placeholder="请输入姓名"> </div>
              <div class="item"><span class="tit">手机：</span><input v-model="addMember.mobile" placeholder="请输入手机号" type="member"></div>
              <div class="item">
                <span class="tit">部门：</span>
                <el-select v-model="addMember.department.id" size="mini" placeholder="请选择">
                  <el-option v-for="item in department" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div>
              <div class="item"><span class="tit">职位：</span><input v-model="addMember.post" size="mini"></div>
              <div class="item"><span class="tit">邮箱：</span><input v-model="addMember.email" size="mini"></div>
              <div class="item"><span class="tit">工号：</span><input v-model="addMember.workNumber" size="mini"></div>
              <div class="submitBox">
                <el-button size="mini" style="color:#3345ff;" @click="dialogVisible = false">取 消</el-button>
                <el-button size="mini" class="submit" type="primary" @click="addMemberSubmit">确 定</el-button>
              </div>
            </div>
            <div v-show="title == '添加部门'" class="itemBox">
              <div class="item"><span class="tit">上级部门：</span>
                <el-select v-model="addDepar.parent.id" size="mini" placeholder="请选择">
                  <el-option v-for="item in department" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div>
              <div class="item"><span class="tit">部门名称：</span><input v-model="addDepar.name" size="mini"></div>
              <div class="submitBox">
                <el-button size="mini" style="color:#3345ff;" @click="dialogVisible = false">取 消</el-button>
                <el-button size="mini" class="submit" type="primary" @click="addDepartment">确 定</el-button>
              </div>
            </div>
            <div v-show="title == '调整部门'" class="itemBox">
              <div class="item"><span class="tit">新部门：</span>
                <el-select v-model="newDeparId" size="mini" placeholder="请选择">
                  <el-option v-for="item in department" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div>
              <div class="submitBox">
                <el-button size="mini" style="color:#3345ff;" @click="dialogVisible = false">取 消</el-button>
                <el-button size="mini" class="submit" type="primary" @click="setDepar">确 定</el-button>
              </div>
            </div>
            <div v-if="dapartmentInfo" v-show="title == '编辑部门'" class="itemBox">
              <div class="item"><span class="tit">上级部门：</span>
                <el-select v-model="dapartmentInfo.parent.id" size="mini" placeholder="请选择">
                  <el-option v-for="item in department" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div>
              <div class="item"><span class="tit">部门名称：</span><input v-model="dapartmentInfo.label" size="mini" placeholder="请输入部门名称"></div>
              <div class="item">
                <span class="tit">设置主管：</span>
                <el-select v-model="dapartmentInfo.manager.id" size="mini" placeholder="请选择">
                  <el-option v-for="item in memberList" :key="item.id" :label="item.username" :value="item.id" />
                </el-select>
              </div>
              <div class="submitBox">
                <el-button size="mini" style="color:#3345ff;" @click="dialogVisible = false">取 消</el-button>
                <el-button size="mini" class="submit" type="primary" @click="dialogSub">确 定</el-button>
              </div>
            </div>
            <div v-show="title == '删除确认'" class="itemBox">
              <div style="text-align: center">
                <p><i class="icon" style="color:#f48181;font-size: 40px;margin: 10px;">&#xe685;</i></p>
                <p>确认后该用户的所有信息将被删除，</p>
                <p>并不可恢复，是否确认删除？</p>
              </div>
              <div class="submitBox">
                <el-button size="mini" style="color:#3345ff;" @click="dialogVisible = false">取 消</el-button>
                <el-button size="mini" class="submit" type="primary" @click="confirmDel">确 定</el-button>
              </div>
            </div>
          </el-dialog>

          <!-- 导入成员 -->

          <el-dialog title="导入通讯录" :visible.sync="importMember" width="80%" :before-close="handleClose">
            <div class="imtTitle">
              <div class="title" style="display: flex">
                <el-upload ref="upload" class="chFile" action="/" :show-file-list="false" :on-change="importExcel" :auto-upload="false">
                  <el-button slot="trigger" icon="el-icon-upload" size="mini" type="primary"> 选择文件 </el-button>
                </el-upload>
                <div>{{ fileName? `${fileName} (文件大小： ${fileSize} KB )`: '请选择需要上传的文件(导入人数小于200人)' }}</div>
              </div>
              <div class="down">
                <a href="https://nineclock-java.oss-cn-zhangjiakou.aliyuncs.com/data/mould/%E9%83%A8%E9%97%A8%E5%91%98%E5%B7%A5%E6%A8%A1%E6%9D%BF.xlsx">下载模板</a>
              </div>
            </div>
            <div class="imtCont">
              <el-table ref="multipleTable" :data="xlsxJson" style="width: 100%" height="450" empty-text="请导入文件" @selection-change="handleSelectionChange">
                <el-table-column prop="姓名" label="姓名" width="90" />
                <el-table-column prop="手机号" label="手机号" width="110" />
                <el-table-column prop="工号" label="工号" width="110" />
                <el-table-column prop="入职时间" label="入职时间" width="100" />
                <el-table-column prop="职位" label="职位" width="100" />
                <el-table-column prop="部门" label="部门" width="100" show-overflow-tooltip />
                <el-table-column prop="办公地点" label="办公地点" width="120" show-overflow-tooltip />
                <el-table-column prop="邮箱" label="邮箱" min-width="110" show-overflow-tooltip />
                <el-table-column prop="角色" label="角色" />
                <el-table-column prop="是否部门主管" label="是否部门主管" width="110" center />
                <el-table-column prop="激活状态" label="激活状态" />
                <el-table-column prop="备注" label="备注" show-overflow-tooltip />
                <el-table-column label="操作" width="80" fixed="right">
                  <template slot-scope="scope">
                    <span class="action" @click="imtDelete(scope.$index)">删除</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="submitBox">
              <el-button size="mini" class="submit" type="primary" @click="uploadFile">上传</el-button>
            </div>
          </el-dialog>

        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import XLSX from 'xlsx'

export default {
  name: 'Dashboard',
  data() {
    return {
      total: 0,
      loading: false,
      page: 1,
      pageSize: 10,
      keyword: '',
      fileName: null,
      fileSize: '',
      title: '添加成员',
      departmentId: '0',
      dapartmentName: '',
      dapartmentInfo: null,
      xlsxJson: [],
      memberList: [],
      companyName: '',
      dialogVisible: false,
      addMember: {
        userName: '',
        mobile: '',
        post: '',
        department: {
          id: ''
        },
        email: '',
        workNumber: ''
      },
      addDepar: {
        name: '',
        parent: {
          id: ''
        }
      },
      delId: '',
      deleteId: '',
      newDeparId: '',
      department: [],
      seldep: '',
      tableData: [],
      importMember: false,
      multipleSelection: [],
      orgList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.init()
    this.getOrgList()
    this.getDepartment()
    this.getSimMember()
  },
  methods: {
    init() {
      const initParams = { page: this.page, pageSize: this.pageSize, keyword: this.keyword, departmentId: this.departmentId }
      this.$store.dispatch('organization/getMemberListAct', initParams).then((res) => {
        this.total = res.total
        this.page = res.page
        this.tableData = res.rows
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    setKeyword(val) {
      this.keyword = val.target.value
    },
    handlePageChange(val) {
      this.page = val
      this.init()
    },
    // 获取组织架构的列表
    getOrgList() {
      this.$store.dispatch('organization/getOrgListAct', { page: this.page, pageSize: this.pageSize }).then((res) => {
        const obj = [{}]
        obj[0].label = res.name
        this.companyName = res.name
        obj[0].id = 0 // 非真正的公司id  这里用的是部门的根ID
        obj[0].children = this.getTreeData(res.departments)
        this.orgList = obj
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取部门成员简单列表
    getSimMember() {
      this.$store.dispatch('organization/getSimMemberAct', { page: 1, pageSize: 1000 }).then((res) => {
        this.memberList = res.rows
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    dialogVisibleHandle(tit, id) {
      if (tit === '调整部门' && !id && this.multipleSelection.length <= 0) {
        this.$message.error('请选择变更部门的人员！')
        return false
      }
      if (tit === '删除确认' && !id && this.multipleSelection.length <= 0) {
        this.$message.error('请选择要删除的人员！')
        return false
      }
      this.addMember = {
        userName: '',
        mobile: '',
        post: '',
        department: {
          id: ''
        },
        email: '',
        workNumber: ''
      }
      this.addDepar.parent.id = this.departmentId
      this.title = tit
      this.dialogVisible = true
      this.delId = id || ''
      this.deleteId = id || ''
    },
    // 删除
    confirmDel(id) {
      const userList = this.multipleSelection.map(n => {
        return n.id
      })
      const user = this.deleteId ? [this.deleteId] : userList
      this.$store.dispatch('organization/delOrgMemberAct', { ids: user }).then((res) => {
        this.$message.success('删除成功！')
        this.dialogVisible = false
        this.init()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleClose(done) {
      done()
    },
    // 获取部门列表
    getDepartment() {
      this.$store.dispatch('organization/getSimOrgAct', { page: 1, includeMember: 1, pageSize: 1000 }).then((res) => {
        this.department = res
        // res.map(n => {
        //   n.type === 0 ? companyId = n.id : null
        // })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 添加成员
    addMemberSubmit() {
      // this.addMember.department.id = this.seldep ? this.seldep : ''
      for (const key in this.addMember) {
        if (key === 'username' && !this.addMember[key].trim()) {
          this.$message.error('姓名不能为空！')
          return false
        } else if (key === 'mobile' && !this.addMember[key].trim() || key === 'mobile' && this.addMember[key].length !== 11) {
          this.$message.error('手机号为空或输入错误！')
          return false
        } else if (key === 'department' && !this.addMember.department.id) {
          this.$message.error('部门不能为空！')
          return false
        } else if (key === 'post' && !this.addMember[key].trim()) {
          this.$message.error('职位不能为空！')
          return false
        } else if (key === 'email' && !this.addMember[key].trim()) {
          this.$message.error('邮箱不能为空！')
          return false
        } else if (key === 'workNumber' && !this.addMember[key].trim()) {
          this.$message.error('工号不能为空！')
          return false
        }
      }

      this.$store.dispatch('organization/addOrgMemberAct', { ...this.addMember }).then((res) => {
        this.$message.success('成员添加成功！')
        this.dialogVisible = false
        this.init()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 添加部门
    addDepartment() {
      if (this.addDepar.parent.id === '') {
        this.$message.error('请选择上级部门！')
        return false
      } else if (!this.addDepar.name.trim()) {
        this.$message.error('部门名称不能为空！')
        return false
      }
      this.$store.dispatch('organization/addOrganizationAct', { ...this.addDepar }).then((res) => {
        this.$message.success('部门添加成功！')
        this.dialogVisible = false
        this.getDepartment()
        this.getOrgList()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 调整部门
    setDepar() {
      const userList = this.multipleSelection.map(n => {
        return { id: n.id }
      })
      const users = this.delId ? [{ id: this.delId }] : userList
      this.$store.dispatch('organization/changeOrganizationAct', { users, department: { id: this.newDeparId }}).then((res) => {
        this.$message.success('部门调整成功！')
        this.dialogVisible = false
        this.getDepartment()
        this.getOrgList()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 编辑部门提交
    dialogSub(val) {
      const dapartmentInfo = this.dapartmentInfo
      const params = { id: dapartmentInfo.id, name: dapartmentInfo.label, manager: { id: dapartmentInfo.manager.id }, parent: { id: dapartmentInfo.parent.id }}
      this.$store.dispatch('organization/putOrganizationAct', params).then((res) => {
        this.$message.success('部门编辑成功！')
        this.dialogVisible = false
        this.getDepartment()
        this.getOrgList()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getTreeData(data) {
      const arr = JSON.stringify(data).replace(/subDepartments/g, 'children').replace(/name/g, 'label')
      return JSON.parse(arr)
    },
    // 点击部门名称
    handleNodeClick(data) {
      this.dapartmentInfo = data.id === 0 ? null : { ...data }
      this.departmentId = data.id
      this.init()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 导入数据删除
    imtDelete(index) {
      this.xlsxJson.splice(index, 1)
    },
    uploadFile() {
      const xlsxJson = this.xlsxJson
      this.$store.dispatch('organization/importMailListACT', { xlsxJson }).then((res) => {
        if (res.success) {
          this.$message.success('上传成功！')
          this.init()
          this.importMember = false
          this.loading = false
        } else {
          this.$message.error(res.message)
        }
      }).catch((error) => {
        this.$message.error(error)
      })
    },
    importExcel(file) {
      // let file = file.files[0] // 使用传统的input方法需要加上这一步
      this.fileName = file.name
      this.fileSize = Math.floor(file.size / 1000)
      if (file.size > 25000) {
        this.$message('文件太大请控制在20KB以内！')
        return
      }
      const types = file.name.split('.')[1]
      const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
      if (!fileType) {
        this.$message('格式错误！请使用下载模板导入!')
        return
      }
      this.file2Xce(file).then(tabJson => {
        if (tabJson && tabJson.length > 0) {
          this.xlsxJson = tabJson[0].sheet
        } else {
          this.$message('文件解析出错！请使用下载模板导入!')
        }
      })
    },
    file2Xce(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        reader.onload = function(e) {
          const data = e.target.result
          this.wb = XLSX.read(data, {
            type: 'binary'
          })
          const result = []
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            })
          })
          resolve(result)
        }
        reader.readAsBinaryString(file.raw)
        // reader.readAsBinaryString(file) // 传统input方法
      })
    }
  }
}
</script>
<style lang="scss">
  .dashboard{
    &-content{
      .el-dialog__body{
        padding: 20px 40px 25px 40px;
      }
      .el-select {
        width: calc(100% - 80px);
      }
      .tableItem{
        .el-table thead th,.el-table thead tr{
          background: #edeffd;
        }
      }
      .pageList{
        .el-pager li{
          margin: 0 5px;
          min-width: 28px;
          width: 28px;
        }
        .active{
          background: #3345ff;
          border-radius: 100%;
          color:#fff;
        }
      }
      .el-button--primary{
        background: #3345ff;
        border-color: #3345ff;
      }
    }
  }
</style>
<style lang="scss" scoped>
  .dashboard {
    &-container{
      /*padding: 15px 0;*/
    }
    &-title {
      padding: 0 15px;
      line-height: 50px;
      background: #edeffd;
      display: flex;
      justify-content: space-between;
      .search{
        width: 250px;
        position: relative;
        input{
          width: 100%;
          border: none;
          border-radius: 3px;
          padding: 4px 25px 4px 10px;
        }
        span{
          cursor:pointer;
          position: absolute;
          color:#666;
          right: 4px;
          top:0;
        }
      }
      .rtList{
        display: flex;
        color:#3345ff;
        font-size: 14px;
        .aLink{
          cursor: pointer;
          padding-left: 10px;
        }
      }
    }
    &-content{
      position: relative;
      .sidebarBox{
        position: fixed;
        height: calc(100vh - 120px);
        padding: 15px 40px;
        left: 0px;
        bottom:0px;
        width: 260px;
        background: #fff;
        .addDepartment{
          cursor:pointer;
          background: #3345ff;
          color:#fff;
          text-align: center;
          line-height: 35px;
          border-radius: 4px;
        }
        .staffTree{
          margin-top: 10px;
        }
      }
      .minCont{
        margin-left: 260px;
        padding:0 15px;
        .contTitle{
          line-height: 50px;
          span{
            color:#3345ff;
            cursor: pointer;
            padding: 0 5px;
            font-size: 14px;
          }
        }
        .tableItem{
          background: #fff;
          .action{
            color:#3345ff;
            cursor:pointer;
          }
          .pageList{
            text-align: right;
            padding: 15px;
          }
        }
      }
      .itemBox{
        .item{
          margin: 10px 0;
          .tit{
            display: inline-block;
          }
          input{
            width: calc(100% - 80px);
            height: 28px;
            border:solid 1px #e8e9ea;
            border-radius: 3px;
            margin-left: 3px;
            padding:0 10px;
            font-size: 14px;
          }
        }
      }
      .imtTitle{
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        .title{
          display: flex;
          position: relative;
          display: inline-block;
          margin-right: 5px;
        }
        .down{
          color: #3345ff;
          cursor: pointer;
        }
        .chFile{
          position: relative;
          margin-right: 10px;
          top:-6px;
        }
      }
      .imtCont{

      }
      .submitBox{
        display: flex;
        justify-content: center;
        margin-top: 20px;
        .submit{
          background: #3345ff;
          border-color:#3345ff;
        }
      }
    }
  }
</style>
